package core.helpers;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

import core.Pilot;

/**
 * Class provides methods for working with CSV files
 */
public class CSVHelper extends FileHelper
{
	private static String pathToFile;
	private final String splitter = ";";

	/**
	 * Constructor
	 * @param p_pilot
	 */
	public CSVHelper(Pilot p_pilot)
	{
		super(p_pilot);
	}

	/**
	 * Writes data to CSV file
	 * @param p_pathToFile
	 * @param p_data
	 */
	public void write(String p_pathToFile, String[] p_data)
	{
		String data = "";
		FileWriter fileWriter = null;

		for (int i = 0; i < p_data.length; i++)
		{
			data += p_data[i] + ";";
		}

		try
		{
			fileWriter = new FileWriter(p_pathToFile, true);
			fileWriter.append(data + "\n");
			fileWriter.close();

			pilot.log().debug("Write data to CSV file [" + p_pathToFile + "]");
		}

		catch (Exception p_exception)
		{
			pilot.log().warn("Cannot write data to CSV file [" + p_pathToFile + "]\nError" + p_exception);
		}
	}

	/**
	 * Write data to CSV file
	 * @param p_filename
	 * @param p_data
	 */
	public void write(String[] p_data)
	{
		write(pathToFile, p_data);
	}

	/**
	 * Gets content from a column
	 * @param p_columnNumber
	 * @return List of strings in the column
	 */
	public String[] readColumn(int p_columnNumber)
	{
		String csvFile = pathToFile;
		BufferedReader bufferReader = null;
		String line = "";
		int linesCount = 0;
		String[] array = null;

		try
		{
			int i = 0;
			bufferReader = new BufferedReader(new FileReader(csvFile));

			while ((line = bufferReader.readLine()) != null)
			{
				linesCount++;
			}

			bufferReader.close();
			array = new String[linesCount];
			bufferReader = new BufferedReader(new FileReader(csvFile));

			i = 0;
			while ((line = bufferReader.readLine()) != null)
			{
				String[] cell = line.split(splitter);
				array[i] = cell[p_columnNumber].trim();

				i++;
			}

			pilot.log().debug("Read the file by column [" + pathToFile + "; " + p_columnNumber + "]");

			return array;
		}
		catch (Exception p_exception)
		{
			pilot.log().warn("Cannot read the file by column [" + pathToFile + "; " + p_columnNumber + "]\nError: " + p_exception);

			return null;
		}
		finally
		{
			close(bufferReader);
		}
	}
}
